﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Warehouse.Web.AppCode;
using System.Web.Script.Serialization;

namespace Warehouse.Web.Purchase
{
    public partial class PaymentView : BasePage
    {
        protected bool IsAdd = false;
        protected bool IsReceipt = false;
        protected DataAccess.PaymentBill PaymentBill = new Warehouse.DataAccess.PaymentBill()
        {
            ReceiptDate = DateTime.Now
        };
        protected List<DataAccess.AssetAccount> Accounts = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.IsAdd = !Request.QueryString.AllKeys.Contains("ID");

                base.RegisterClientScriptContent("allsupplier", new JavaScriptSerializer().Serialize(DataAccess.Supplier.GetSuppliers()));

                this.ddlTransactor.DataSource = new List<DataAccess.User>(new DataAccess.User[] { new DataAccess.User(){
                    LoginName=string.Empty,
                    Name="请选择"
                }}).Concat(DataAccess.User.GetList());
                this.ddlTransactor.DataBind();

                this.Accounts = new List<Warehouse.DataAccess.AssetAccount>(DataAccess.AssetAccount.GetAssetAccounts());
                this.Accounts.Insert(0, DataAccess.AssetAccount.Empty);

                if (!IsAdd)
                {
                    Guid billId = new Guid(Request.QueryString["ID"]);
                    this.PaymentBill = DataAccess.PaymentBill.GetOne(billId);
                    this.IsReceipt = this.PaymentBill.IsIncome;

                    this.rptDetails.DataSource = DataAccess.PaymentDetail.GetList(p => p.BillID == billId);
                    this.rptDetails.DataBind();

                    for (int i = 0; i < this.ddlTransactor.Items.Count; i++)
                    {
                        if (this.ddlTransactor.Items[i].Value == this.PaymentBill.Transactor)
                        {
                            this.ddlTransactor.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else
                {
                    this.IsReceipt = !string.IsNullOrEmpty(Page.Request.QueryString["receipt"]);
                    this.rptDetails.DataSource = Enumerable.Range(0, 10).Select(p => new
                    {
                        ID = 0,
                        Amount = "",
                        Comments = ""
                    }).ToArray();
                    this.rptDetails.DataBind();
                }
                SetView();
            }
        }

        void SetView()
        {
            if (IsAdd)
            {
                this.acSavePayment.Visible = false;
                this.acSaveReceipt.Visible = false;
                this.acAddPayment.Visible = !this.IsReceipt;
                this.acAddReceipt.Visible = this.IsReceipt;
            }
            else
            {
                base.RegisterClientScriptContent("", "window.EditModel=true;");

                this.acSavePayment.Visible = !this.IsReceipt && this.PaymentBill.BillStatus == Warehouse.DataAccess.BillStatus.Default;
                this.acSaveReceipt.Visible = this.IsReceipt && this.PaymentBill.BillStatus == Warehouse.DataAccess.BillStatus.Default;
                this.acAddPayment.Visible = false;
                this.acAddReceipt.Visible = false;
            }
        }

        protected override void ProcessAjaxRequest(HttpContext context, string action)
        {
            switch (action)
            {
                case "AddPayment":
                case "AddReceipt":
                    {
                        var bill = GetBill(context);
                        bill.ID = Guid.NewGuid();
                        bill.CreateDate = DateTime.Now;
                        bill.Creator = context.User.Identity.Name;
                        bill.BillStatus = Warehouse.DataAccess.BillStatus.Default;
                        bill.IsIncome = action == "AddReceipt";

                        var details = GetDetails(context);
                        foreach (var d in details)
                        {
                            d.BillID = bill.ID;
                        }

                        using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                        {
                            using (DataAccess.WarehouseClassesDataContext datacontext = new Warehouse.DataAccess.WarehouseClassesDataContext())
                            {
                                bill.Save(datacontext);
                                foreach (var d in details)
                                {
                                    d.Save(datacontext);
                                }
                            }
                            scope.Complete();
                        }
                        WebUtil.WriteJsonResult(context, null);
                    }
                    break;
                case "SaveReceipt":
                case "SavePayment":
                    {
                        JavaScriptSerializer ser = new JavaScriptSerializer();
                        DataAccess.PaymentBill bill = ser.Deserialize<DataAccess.PaymentBill>(context.Request.Form["Bill"]);
                        DataAccess.PaymentDetail[] details = ser.Deserialize<DataAccess.PaymentDetail[]>(context.Request.Form["Details"]);

                        var oldBill = DataAccess.PaymentBill.GetOne(bill.ID);
                        oldBill.Summary = bill.Summary;
                        oldBill.Comments = bill.Comments;
                        oldBill.Save();
                        foreach (var d in details)
                        {
                            var oldDetail = DataAccess.PaymentDetail.GetOne(d.ID);
                            oldDetail.Comments = d.Comments;
                            oldDetail.Save();
                        }
                        WebUtil.WriteJsonResult(context, null);
                    }
                    break;
                case "InvalidPayment":
                case "InvalidReceipt":
                    {
                        Guid billId = new Guid(context.Request.Form["ID"]);
                        DataAccess.PaymentBill bill = DataAccess.PaymentBill.GetOne(billId);
                        bill.BillStatus = Warehouse.DataAccess.BillStatus.Invalid;

                        if (bill.PruchageBillID.HasValue)
                        {
                            DataAccess.PurchaseBill purcharsebill = DataAccess.PurchaseBill.GetOne(bill.PruchageBillID.Value);
                            purcharsebill.BillStatus = Warehouse.DataAccess.BillStatus.Invalid;

                            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                            {
                                using (DataAccess.WarehouseClassesDataContext datacontext = new Warehouse.DataAccess.WarehouseClassesDataContext())
                                {
                                    bill.Save(datacontext);
                                    purcharsebill.Save(datacontext);
                                }
                                scope.Complete();
                            }
                        }
                        else
                        {
                            bill.Save();
                        }
                        WebUtil.WriteJsonResult(context, null);
                    }
                    break;
                default:
                    base.ProcessAjaxRequest(context, action);
                    break;
            }
        }

        protected void rptDetails_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            var ddlAccount = e.Item.FindControl("ddlAccount") as DropDownList;
            if (ddlAccount != null)
            {
                ddlAccount.DataSource = this.Accounts;
                ddlAccount.DataBind();

                DataAccess.PaymentDetail detail = e.Item.DataItem as DataAccess.PaymentDetail;
                if (detail != null)
                {
                    ddlAccount.SelectedIndex = this.Accounts.FindIndex(p => p.ID == detail.AccountID);
                }
            }
        }

        static DataAccess.PaymentBill GetBill(HttpContext context)
        {
            DataAccess.PaymentBill bill = new JavaScriptSerializer().Deserialize<DataAccess.PaymentBill>(context.Request.Form["Bill"]);
            bill.SerialNumber = bill.SerialNumber.Trim();
            bill.Transactor = bill.Transactor.Trim();
            if (string.IsNullOrEmpty(bill.SerialNumber))
            {
                throw new ApplicationException("单据编号不能为空");
            }
            if (bill.SupplierID <= 0)
            {
                throw new ApplicationException("供货商不能为空");
            }
            if (string.IsNullOrEmpty(bill.Transactor))
            {
                throw new ApplicationException("经手人不能为空");
            }
            return bill;
        }

        static DataAccess.PaymentDetail[] GetDetails(HttpContext context)
        {
            DataAccess.PaymentDetail[] details = new JavaScriptSerializer().Deserialize<DataAccess.PaymentDetail[]>(context.Request.Form["Details"]);

            if (details.Length == 0)
            {
                throw new ApplicationException("帐号不能为空");
            }
            foreach (var d in details)
            {
                if (d.AccountID <= 0)
                {
                    throw new ApplicationException("帐号不能为空");
                }
                if (d.Amount < 0)
                {
                    throw new ApplicationException("金额不能为负数");
                }
            }
            return details;
        }

    }
}
